﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using LimaLims.Application.Service.Base.Dto;
using LimaLims.Application.Service.Basic.Dto;
using LimaLims.Application.Service.Sys;
using LimaLims.Core;
using LimaLims.Core.Entity.Basic;
using LimaLims.Core.Enum;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LimaLims.Application.Service.Basic
{

    /// <summary>
    /// 处理意见
    /// </summary>
    [ApiDescriptionSettings(Name = "DealOpinion", Order = 165)]
    [Route("api")]
    public class DealOpinionService : IDealOpinionService, IDynamicApiController, ITransient
    {
        private readonly IRepository<DealOpinion> _dealOpinionRep;  // 处理意见仓储
        private readonly IGenerateCodeUtilService _generateCodeUtilService;//编码规则

        public DealOpinionService(IRepository<DealOpinion> dealOpinionRep, IGenerateCodeUtilService generateCode)
        {
            _dealOpinionRep = dealOpinionRep;
            _generateCodeUtilService = generateCode;
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("dealOpinion/add")]
        public async Task Add(AddDealOpinionInput input)
        {
            var isExist = await _dealOpinionRep.DetachedEntities.AnyAsync(u => u.Code == input.Code);
            if (isExist)
                throw Oops.Oh("已存在相同编号的处理意见！");

            if (string.IsNullOrWhiteSpace(input.Code))
            {
                input.Code = await _generateCodeUtilService.GenerateCode(BusinessType.DealOpinion);
            }

            var dealOpinion = input.Adapt<DealOpinion>();

            await dealOpinion.InsertAsync();
        }

        [HttpPost("dealOpinion/delete")]
        public async Task Delete(long id)
        {
            var dealOpinion = await _dealOpinionRep.FirstOrDefaultAsync(u => u.Id == id);
            if (dealOpinion == null)
                throw Oops.Oh("不存在此数据");

            await dealOpinion.DeleteAsync();
        }

        [HttpGet("dealOpinion/detail")]
        public async Task<DealOpinion> Detail(long id)
        {
            var dealOpinion = await _dealOpinionRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (dealOpinion == null)
                throw Oops.Oh("不存在此数据");

            return dealOpinion;
        }

        [HttpPost("dealOpinion/edit")]
        public async Task Edit(EditDealOpinionInput input)
        {
            var dealOpinion = await _dealOpinionRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (dealOpinion == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _dealOpinionRep.DetachedEntities.AnyAsync(u => u.Code == input.Code && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在相同编号的处理意见！");

            var dealOpinionModel = input.Adapt<DealOpinion>();

            await dealOpinionModel.UpdateAsync();
        }

        /// <summary>
        /// 下拉数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("dealOpinion/selectList")]
        public async Task<List<SelectFilterDto>> SelectList()
        {
            var list = await _dealOpinionRep.DetachedEntities.Where(s => s.ValidStatus == true).OrderBy(s => s.Sort).ToListAsync();
            return list.Select(x => new SelectFilterDto
            {
                IsFilter = x.IsAssess,
                Value = x.Id,
                Label = x.Opinion
            }).ToList();
        }

        [HttpGet("dealOpinion/page")]
        public async Task<PageResult<DealOpinionOutput>> QueryPage([FromQuery] DealOpinionPageInput input)
        {
            var name = !string.IsNullOrEmpty(input.SearchValue?.Trim());
            var code = !string.IsNullOrEmpty(input.Code?.Trim());
            var items = await _dealOpinionRep.DetachedEntities
                                         .Where((name, u => EF.Functions.Like(u.Opinion, $"%{input.SearchValue.Trim()}%")))
                                         .Where((code, u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%")))
                                         .Where(input.ValidStatus.HasValue, u => u.ValidStatus == input.ValidStatus)
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new DealOpinionOutput
                                         {
                                             Id = u.Id,
                                             Code = u.Code,
                                             Opinion = u.Opinion,
                                             ValidStatus = u.ValidStatus,
                                             IsAssess = u.IsAssess,
                                             Sort = u.Sort,
                                             Remark = u.Remark,
                                             CreatedTime = u.CreatedTime,
                                             CreatedUserName = u.CreatedUserName,
                                             UpdatedTime = u.UpdatedTime,
                                             UpdatedUserName = u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return items;
        }

    }
}
